package org.walklink.core.plugins.request;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.walklink.common.util.slidewin.DefaultSlideWinLimiter;
import org.walklink.core.inject.CommonInject;

import java.util.concurrent.atomic.AtomicBoolean;


/**
 * 客户端限制性（如：每秒限制多少个请求）请求插件
 *
 * @author lidishan
 */
public class LimitClientRequestPlugin implements IClientRequestPlugin {

    private static final Logger LOGGER = LogManager.getLogger(LimitClientRequestPlugin.class);

    /**
     * 是否打印限流出现的日志
     */
    private static final AtomicBoolean IS_HIDE_OVER_LIMIT_LOG = new AtomicBoolean(false);


    @Override
    public boolean passRequest() {
        // 初始化默认滑动窗口
        DefaultSlideWinLimiter rateLimiter = CommonInject.getInstance(DefaultSlideWinLimiter.class);
        boolean overLimit = rateLimiter.isOverLimit();
        if (overLimit
                && IS_HIDE_OVER_LIMIT_LOG.compareAndSet(false, true)) {
            LOGGER.info("LimitClientRequestPlugin passRequest is over limit");
            return false;
        }

        // 走到这步，没有进行限流，打个log
        if (IS_HIDE_OVER_LIMIT_LOG.get()
                && IS_HIDE_OVER_LIMIT_LOG.compareAndSet(true, false)) {
            LOGGER.info("LimitClientRequestPlugin passRequest is recover");
        }

        return true;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
